package com.study.volatile_study;

/**
 * https://blog.csdn.net/qq_42225507/article/details/107347472
 */
public class VolatileTest {
    static class A {
        static int a = 0;
        volatile boolean flag = false;

        void writer() {
            System.out.println(Thread.currentThread());
            a = 1;                   //1
            flag = true;               //2
            System.out.println("write");
        }

        void reader(String name) {
            System.out.println(Thread.currentThread() + "_" + name);
            if (flag) {                //3
                int i =  a;           //4
                System.out.println("read true");
                System.out.println("i is :" + i);
            } else {
                int i = a;
                System.out.println("read false");
                System.out.println("i is :" + i);
            }
            a++;
        }

    }

    public static void main(String[] args) throws InterruptedException {
        A aaa = new A();
        A bbb = new A();
        /*
        new Thread(() -> aaa.reader()).start();
        new Thread(() -> aaa.writer()).start();

        new Thread(() -> aaa.reader()).start();
        new Thread(() -> aaa.reader()).start();
        new Thread(() -> aaa.reader()).start();*/
        Thread t1 = new Thread(() -> aaa.reader("t1a"));
        t1.start();
        t1.join();
        Thread t2 = new Thread(() -> aaa.writer());
        t2.start();
        t2.join();

        Thread t4 = new Thread(() -> bbb.reader("t4b"));
        Thread t5 = new Thread(() -> bbb.reader("t5b"));
        Thread t3 = new Thread(() -> aaa.reader("t3a"));
        t4.start();
        t4.join();
        t3.start();
        t3.join();
        t5.start();
//        t3.start();
//        t3.start();
//        t4.join();

        Thread.sleep(1000L);

//        new Thread(() -> bbb.reader()).start();
//        new Thread(() -> bbb.reader()).start();
//        new Thread(() -> bbb.reader()).start();
    }
}